package cn.itrip.biz.controller;

import cn.itrip.beans.dtos.Dto;
import cn.itrip.beans.pojo.ItripComment;
import cn.itrip.beans.pojo.ItripImage;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripImageVO;
import cn.itrip.beans.vo.comment.ItripAddCommentVO;
import cn.itrip.beans.vo.comment.ItripListCommentVO;
import cn.itrip.beans.vo.comment.ItripSearchCommentVO;
import cn.itrip.biz.service.itripComment.ItripCommentService;
import cn.itrip.biz.service.itripImage.ItripImageService;
import cn.itrip.common.*;
import org.springframework.beans.BeanUtils;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.*;

@Controller
@RequestMapping("/api/comment")
public class SystemCommentController {
    @Resource
    private ItripImageService itripImageService;
    @Resource
    private ItripCommentService itripCommentService;
    @Resource
    private ValidationToken validationToken;
    @Resource
    private SystemConfig systemConfig;

    @RequestMapping(value = "/getimg/{targetId}", method = RequestMethod.GET, produces = "application/json")
    @ResponseBody
    public Dto<List<ItripImageVO>> getImg(@PathVariable String targetId) throws Exception{
        if(EmptyUtils.isEmpty(targetId)){
            return DtoUtil.returnFail("评论id不能为空", "100013");
        }
        Map<String, Object> param = new HashMap<>();
        param.put("targetId", Long.valueOf(targetId));
        param.put("type", "2");
        try {
            List<ItripImage> imageList = itripImageService.getItripImageListByMap(param);
            List<ItripImageVO> result = new ArrayList<>();
            if(EmptyUtils.isNotEmpty(imageList)){
                ItripImageVO itripImageVO = null;
                for(ItripImage image : imageList){
                    itripImageVO = new ItripImageVO();
                    BeanUtils.copyProperties(image, itripImageVO);
                    result.add(itripImageVO);
                }
            }
            return DtoUtil.returnDataSuccess(result);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取评论图片失败", "100012");
        }
    }

    @RequestMapping(value = "/getcommentlist", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<Page<ItripListCommentVO>> getCommentList(@RequestBody ItripSearchCommentVO itripSearchCommentVO) throws Exception{
        if(itripSearchCommentVO == null ||
                (itripSearchCommentVO.getHotelId() == null
                || itripSearchCommentVO.getHotelId() == 0)
                ||(itripSearchCommentVO.getIsHavingImg() == null)
                ||(itripSearchCommentVO.getIsOk() == null)
                ||(itripSearchCommentVO.getPageNo() == null)
                ||(itripSearchCommentVO.getPageSize() == null)){
            return DtoUtil.returnFail("表单数据不完整", "100021");
        }
        if(itripSearchCommentVO.getIsOk() == -1){
            itripSearchCommentVO.setIsOk(null);
        }
        if(itripSearchCommentVO.getIsHavingImg() == -1){
            itripSearchCommentVO.setIsHavingImg(null);
        }
        Map<String, Object> param = new HashMap<>();
        param.put("hotelId", itripSearchCommentVO.getHotelId());
        param.put("isHavingImg", itripSearchCommentVO.getIsHavingImg());
        param.put("isOk", itripSearchCommentVO.getIsOk());
        try {
            Page page = itripCommentService.queryItripCommentPageByMap(param,
                    itripSearchCommentVO.getPageNo(),
                    itripSearchCommentVO.getPageSize());
            return DtoUtil.returnDataSuccess(page);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("获取评论列表错误", "100020");
        }
    }

    //上传评价图片
    @RequestMapping(value = "/upload", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto<List<String>> uploadPic(HttpServletRequest request, HttpServletResponse response) throws Exception{
        List<String> hasError = new ArrayList<>();
        List<String> result = new ArrayList<>();
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if(multipartResolver.isMultipart(request)){
            //处理文件上传
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;
            //表单验证
            String token = multipartRequest.getHeader("token");
            String agent = multipartRequest.getHeader("user-agent");
            if(!validationToken.validateToken(token, agent)){
                return DtoUtil.returnFail("token无效，请重新登录","100000");
            }
            int fileCount = 0;//文件数量
            try {
                fileCount = multipartRequest.getMultiFileMap().size();
            } catch (Exception e) {
                e.printStackTrace();
                return DtoUtil.returnFail("文件大小超限","100009");
            }
            if(fileCount <= 4){
                //读文件
                //获得文件名，文件类型（用于新文件名的后缀）
                //验证文件类型
                //保存文件：不能用文件原名， --> 用户id-系统时间毫秒数-随机数.后缀
                //存到服务器指定目录
                Iterator<String> names = multipartRequest.getFileNames();
                ItripUser user = validationToken.getCurrentUser(token);
                while(names.hasNext()){
                    String orginFileName = null;
                    try {
                        MultipartFile file = multipartRequest.getFile(names.next());
                        if(file != null){
                            orginFileName = file.getOriginalFilename();
                            String suffix = orginFileName.substring(orginFileName.lastIndexOf(".")).toLowerCase();
                            if(!orginFileName.equals("")
                            &&(suffix.equals(".jpg")
                                    || suffix.equals(".png")
                                    || suffix.equals(".jpeg"))){
                                //新文件名
                                String fileRename = user.getId()+
                                        "-"+System.currentTimeMillis()+
                                        "-"+(int)(Math.random()*100000000)+suffix;
                                //完整保存路径
                                String fullPath = systemConfig.getFileUploadPathString() + File.separator + fileRename;
                                file.transferTo(new File(fullPath));
                                result.add(systemConfig.getVisitImgUrlString() + fileRename);
                            }else{
                                hasError.add(orginFileName+"上传失败，不允许的文件类型"+suffix);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        hasError.add(orginFileName+"上传失败，请重新上传");
                    }
                }
                if(hasError.isEmpty()){
                    return DtoUtil.returnDataSuccess(result);
                }else{
                    return DtoUtil.returnSuccess(hasError.toString(), result);
                }
            }else{
                return DtoUtil.returnFail("上传的文件数不正确，必须是大于1小于等于4","100007");
            }
        }else{
            return DtoUtil.returnFail("请求的内容不是上传文件的类型","100008");
        }
    }

    @RequestMapping(value = "/delpic", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto delPic(@RequestParam String imgName, HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        if(!validationToken.validateToken(token, agent)){
            return DtoUtil.returnFail("token无效，请重新登录", "100000");
        }
        //获得文件在服务器上的物理路径
        String fullPath = systemConfig.getFileUploadPathString()+File.separator+imgName;
        File file = new File(fullPath);
        if(file.exists()){
            file.delete();
            return DtoUtil.returnSuccess("删除成功");
        }else{
            return DtoUtil.returnFail("文件不存在，删除失败","100010");
        }
    }

    @RequestMapping(value = "/add", method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Dto addComment(@RequestBody ItripAddCommentVO itripAddCommentVO, HttpServletRequest request) throws Exception{
        String token = request.getHeader("token");
        String agent = request.getHeader("user-agent");
        if(!validationToken.validateToken(token, agent)){
            return DtoUtil.returnFail("token无效，请重新登录", "100000");
        }
        if(itripAddCommentVO == null || itripAddCommentVO.getOrderId() == null
        || itripAddCommentVO.getOrderId() == 0){
            return DtoUtil.returnFail("新增评论，订单ID不能为空","100005");
        }
        if(itripAddCommentVO.getHotelId() == null
                || itripAddCommentVO.getProductId() == null
                || itripAddCommentVO.getProductType() == null
                || itripAddCommentVO.getIsHavingImg() == null
                || itripAddCommentVO.getPositionScore() == null
                || itripAddCommentVO.getFacilitiesScore() == null
                || itripAddCommentVO.getServiceScore() == null
                || itripAddCommentVO.getHygieneScore() == null
                || itripAddCommentVO.getTripMode() == null
                || itripAddCommentVO.getIsOk() == null){
            return DtoUtil.returnFail("不能提交空，请填写评论信息","100004");
        }
        ItripComment itripComment = new ItripComment();
        BeanUtils.copyProperties(itripAddCommentVO, itripComment);
        itripComment.setTripMode(Long.valueOf(itripAddCommentVO.getTripMode()));
        ItripUser user = validationToken.getCurrentUser(token);
        itripComment.setCreatedBy(user.getId());
        itripComment.setCreationDate(new Date());
        itripComment.setUserId(user.getId());
        List<ItripImage> itripImages = new ArrayList<>();
        if(itripAddCommentVO.getIsHavingImg() == 1){
            int i = 0;
            for(ItripImage image:itripAddCommentVO.getItripImages()){
                image.setCreationDate(itripComment.getCreationDate());
                image.setCreatedBy(itripComment.getCreatedBy());
                image.setPosition(++i);
                image.setType("2");
//              image.setTargetId();
                itripImages.add(image);
            }
        }
        try {
            itripCommentService.itriptxAddItripComment(itripComment, itripImages);
            return DtoUtil.returnSuccess("新增评论成功");
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("新增评论失败","100003");
        }
    }
}
